<?php

/**
 * This is the model class for table "mj_jobs".
 *
 * The followings are the available columns in table 'mj_jobs':
 * @var integer $id
 * @var string $title
 * @var string $content
 * @var string $tags
 * @var integer $status
 * @var integer $create_time
 * @var integer $update_time
 * @var integer $author_id
 */
class Resume extends CActiveRecord
{
    const STATUS_PENDING=1;
	const STATUS_APPROVED=2;

    private $_statuses;
    private $_oldTags;

    public $email;
    public $name;

	/**
	 * Returns the static model of the specified AR class.
	 * @return Job the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{resume}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
        if (Yii::app()->user->isGuest) {
            return array(
			    array('title, content, email, name', 'required'),
                array('email', 'email'),
                array('name', 'length', 'max'=>128),
    			array('status', 'in', 'range'=>array(1,2)),
	        	array('title', 'length', 'max'=>128),
                array('tags', 'length', 'max'=>500),
			    array('tags', 'normalizeTags'),

			    array('title, status', 'safe', 'on'=>'search'),
		    );
        } else {
		    return array(
			    array('title, content', 'required'),
    			array('status', 'in', 'range'=>array(1,2)),
	        	array('title', 'length', 'max'=>128),
			    array('tags', 'length', 'max'=>500),
                array('tags', 'normalizeTags'),

			    array('title, status', 'safe', 'on'=>'search'),
		    );
        }
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'author' => array(self::BELONGS_TO, 'User', 'author_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'Id',
            'email' => Yii::t('mj-base', 'Email'),
            'name' => Yii::t('mj-base', 'Name'),
			'title' => Yii::t('mj-base', 'Title'),
			'content' => Yii::t('mj-base', 'Content'),
			'tags' => Yii::t('mj-base', 'Tags'),
			'status' => Yii::t('mj-base', 'Status'),
			'create_time' => Yii::t('mj-base', 'Create Time'),
			'update_time' => Yii::t('mj-base', 'Update Time'),
			'author_id' => Yii::t('mj-base', 'Author'),
		);
	}

    /*
     * Return statuses for form
     */
    public function getStatuses()
    {
        if ($this->_statuses == null) {
            $this->_statuses = array(
                Job::STATUS_PENDING=>Yii::t('mj-base', 'Pending'),
                Job::STATUS_APPROVED=>Yii::t('mj-base', 'Approved'),
            );
        }
        return $this->_statuses;
    }

    public function getIsOwner()
    {
        if (Yii::app()->user->isGuest)
            return false;
        else
            return (Yii::app()->user->id == $this->author_id);
    }

	/**
	 * @return string the URL that shows the detail of the post
	 */
	public function getUrl()
	{
		return Yii::app()->urlManager->createUrl('resume/view', array(
			'id'=>$this->id,
			'title'=>$this->title,
		));
	}

    public function getAbsoluteUrl()
    {
        return Yii::app()->getRequest()->getHostInfo().$this->getUrl();
    }

    public function getAdminLinks()
    {
        $links = '';
        $urlManager = Yii::app()->urlManager;
        if ($this->status != Resume::STATUS_APPROVED) {
            $links .= CHtml::ajaxLink(Yii::t('mj-base', 'Approve'),
                                      $urlManager->createUrl('resume/approve'),
                                      array('type' =>'POST', 'data'=>array('id'=>$this->id),
                                           'success'=>'function (){$("#j'.$this->id.'").addClass("item-approved");}'));
        }
        $links .= CHtml::link(Yii::t('mj-base', 'Remove'),
                              '#', array('onclick'=>'$("#decline-id").val("'.$this->id.'");$("#moderationDialog").dialog("open"); return false;'));
        return $links;
    }

	/**
	 * @return array a list of links that point to the post list filtered by every tag of this post
	 */
	public function getTagLinks()
	{
		$links=array();
		foreach(JTag::string2array($this->tags) as $tag)
			$links[]=CHtml::link(CHtml::encode($tag), array('resume/index', 'tags'=>$tag));
		return $links;
	}

	/**
	 * Normalizes the user-entered tags.
	 */
	public function normalizeTags($attribute,$params)
	{
		$this->tags=JTag::array2string(array_unique(JTag::string2array($this->tags)));
	}

	/**
	 * This is invoked when a record is populated with data from a find() call.
	 */
	protected function afterFind()
	{
		parent::afterFind();
		$this->_oldTags=$this->tags;
	}

	/**
	 * This is invoked before the record is saved.
	 * @return boolean whether the record should be saved.
	 */
	protected function beforeSave()
	{
		if(parent::beforeSave())
		{
			if($this->isNewRecord)
			{
                if ($this->author_id == null) {
                    if (Yii::app()->user->isGuest) {
                        $user = User::getUser($this->email, $this->name, true);
                        if ($user->status == User::STATUS_ACTIVE or $user->status == User::STATUS_BANED) {
                            $this->addError('email', 'Login for access to activated account');
                            return false;
                        }
                        $this->author_id = $user->id;
                    } else {
                        if (UserModule::user()->status == User::STATUS_BANED) {
                            $this->addError('email', 'You are banned. Contact Administrator for more information');
                            return false;
                        }
                        $this->author_id = Yii::app()->user->id;
                    }
                }
                if (UserModule::isAdmin() or Yii::app()->params['itemsNeedApproval'] == false) {
                    $this->status = Resume::STATUS_APPROVED;
                } else {
                    $this->status = Resume::STATUS_PENDING;
                }
                if ($this->create_time == null)
				    $this->create_time=$this->update_time=time();
			}
			else
				$this->update_time=time();
			return true;
		}
		else
			return false;
	}

	/**
	 * This is invoked after the record is saved.
	 */
	protected function afterSave()
	{
		parent::afterSave();
		JTag::model()->updateFrequency($this->_oldTags, $this->tags);
	}

	/**
	 * This is invoked after the record is deleted.
	 */
	protected function afterDelete()
	{
		parent::afterDelete();
		JobRequest::model()->deleteAll('job_id='.$this->id);
		JTag::model()->updateFrequency($this->tags, '');
	}

	/**
	 * Retrieves the list of posts based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the needed posts.
	 */
	public function search()
	{
		$criteria=new CDbCriteria;

		$criteria->compare('title',$this->title,true);

		$criteria->compare('status',$this->status);

		return new CActiveDataProvider('Job', array(
			'criteria'=>$criteria,
			'sort'=>array(
				'defaultOrder'=>'status, update_time DESC',
			),
		));
	}
}
